//
//  KY_MyFavViewController.m
//  ShaQueVideo
//
//  Created by huliang on 13-5-9.
//  Copyright (c) 2013年 科悦信达. All rights reserved.
//

#import "KY_MyFavViewController.h"
#import "KY_VideoDetailViewController.h"
#import "KY_WeiBoActionSheet.h"
@interface KY_MyFavViewController ()

@end

@implementation KY_MyFavViewController
@synthesize adView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"我的收藏";
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated
{
//    [self.adView removeFromSuperview];
//    [self.adView setDelegate:nil];
//    self.adView = nil;

}
-(void)dealloc
{
    [super dealloc] ;
        [self.adView removeFromSuperview];
        [self.adView setDelegate:nil];
        self.adView = nil;
}
-(void)viewWillAppear:(BOOL)animated
{
    [self setArray];

}
-(void)setArray
{
    self.listArr = [NSArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"]];
    [self.tableView reloadData];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:GLOBAL_VIEW_BG_COLOR];
    self.title = @"我的收藏";
    self.adView = [AdViewView requestAdViewViewWithDelegate:self];
    [self.view addSubview:self.adView];
    [self.tableView setFrame:CGRectMake(0, self.adView.frame.size.height, 320, self.view.frame.size.height-self.adView.frame.size.height)];
}

- (NSString*) adViewApplicationKey {

    return @"SDK201312081206290g605c5qaeugil1";

    // 在 AdView ⺴⽹网站申请的 key.
}
- (UIViewController*) viewControllerForPresentingModalView {

    //    KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
    //
    //    return  delegate.tabBarController;
    //
    return self;
    // 全屏⼲⼴广告附着的控制器.
}
- (BOOL) adViewTestMode {

    return NO;

    //在测试时返回 YES;
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSDictionary *dict = [self.listArr objectAtIndex:indexPath.row];
    KY_VideoDetailViewController *detailView = [[KY_VideoDetailViewController alloc] initWithVideoURL:[dict objectForKey:@"playurl"]];
    [self presentModalViewController:detailView animated:YES];
    [detailView release];

    NSArray *historyArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"history"];
    NSString *playUrl = [[self.listArr objectAtIndex:indexPath.row] objectForKey:@"playurl"];

    for (NSDictionary *dic in historyArray) {

        if ([[dic objectForKey:@"playurl"] isEqualToString:playUrl]) {

            return;
        }
    }
    NSMutableArray *m_array = [NSMutableArray arrayWithArray:historyArray];
    [m_array addObject:[self.listArr objectAtIndex:indexPath.row]];
    [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"history"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 124;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.listArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identify = @"detaillistcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if(cell == nil){
        NSArray *nibArr = [[NSBundle mainBundle] loadNibNamed:@"KY_VideoListTableCell" owner:self options:nil];
        cell = (UITableViewCell *)[ nibArr objectAtIndex:0];
    }

    UIImageView *img;  UITextView *descTextView;  NSDictionary *dict;

    dict = [self.listArr objectAtIndex:indexPath.row];
    // UIView  *bgView = (UIImageView *)[cell viewWithTag:1];
    //    if( (indexPath.row % 2) != 0){
    //        bgView.hidden = NO;
    //    }else{
    //        bgView.hidden = YES;
    //    }
    UIButton *shareBtn = (UIButton *)[cell viewWithTag:99];
    shareBtn.accessibilityValue =  [NSString stringWithFormat:@"%d",indexPath.row];
    [shareBtn addTarget:self action:@selector(shareWeiBo:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *shoucangBtn = (UIButton *)[cell viewWithTag:98];
    NSString *playUrl = [[self.listArr objectAtIndex:indexPath.row] objectForKey:@"playurl"];
    NSArray *m_array = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"];

    for (NSDictionary *dic in m_array) {

        if ([[dic objectForKey:@"playurl"] isEqualToString:playUrl]) {

            [shoucangBtn setTitle:@"已收藏" forState:UIControlStateNormal];
            shoucangBtn.tag = 89;
            break;
        }
    }

    shoucangBtn.accessibilityValue = [NSString stringWithFormat:@"%d",indexPath.row];
    [shoucangBtn addTarget:self action:@selector(collectVideo:) forControlEvents:UIControlEventTouchUpInside];

    img = (UIImageView *)[cell viewWithTag:11];
    NSURL *url = [NSURL URLWithString:[dict objectForKey:@"icon"]];
    [img setImageWithURL:url placeholderImage:nil];

    descTextView = (UITextView *)[cell viewWithTag:10];
    descTextView.text = [dict objectForKey:@"title"];

    return cell;
}
-(void)collectVideo:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"];
    if (button.tag == 98) {

        NSMutableArray *m_array = [NSMutableArray arrayWithArray:array];
        [m_array addObject:[self.listArr objectAtIndex:[button.accessibilityValue intValue]]];

        [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"favourite"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [button setTitle:@"已收藏" forState:UIControlStateNormal];
        button.tag = 89;
    }
    else if(button.tag == 89)
    {
        NSMutableArray *m_array = [NSMutableArray arrayWithArray:array];

        for (NSDictionary *dic in m_array) {

            if ([[dic objectForKey:@"playurl"] isEqualToString:[[self.listArr objectAtIndex:[button.accessibilityValue intValue]] objectForKey:@"playurl"]]) {

                [m_array removeObject:dic];
                break;

            }
        }

        [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"favourite"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [button setTitle:@"收藏" forState:UIControlStateNormal];
        button.tag = 98;
    }
    [self setArray];
}

-(void)shareWeiBo:(id)sender{

    UIButton *button = (UIButton *)sender;
    self.sharedNum = [button.accessibilityValue intValue];

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择设备"  delegate:self
                                              cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];


    [sheet addButtonWithTitle:@"分享到新浪微博"];
    [sheet addButtonWithTitle:@"分享到微信"];
    [sheet addButtonWithTitle:@"分享到朋友圈"];
    [sheet addButtonWithTitle:@"取消"];
    sheet.cancelButtonIndex = sheet.numberOfButtons-1;
    // [sheet addButtonWithTitle:@"本地播放"];
    [sheet showFromRect:self.view.bounds inView:self.tabBarController.view animated:YES];

}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{



    if (buttonIndex == 0) {


        SinaWeibo *sinaweibo = [self sinaweibo];
        [sinaweibo logIn];


    }
    else if (buttonIndex == 1)
    {
        KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
        delegate.sinaOrWeixin = YES;
        _scene = WXSceneSession;

        [self sendVideoContent];
    }
    else if (buttonIndex == 2)
    {
        KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];

        delegate.sinaOrWeixin = YES;
        _scene = WXSceneTimeline;

        [self sendVideoContent];
    }


}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];

    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    [self storeAuthData];
    TextViewController *viewController = [[TextViewController alloc] init];
    NSString *str = [NSString stringWithFormat:@"不看是你的损失哦！！！%@ %@",[[self.listArr objectAtIndex:self.sharedNum] objectForKey:@"title"],[[self.listArr objectAtIndex:self.sharedNum] objectForKey:@"sourceurl"]];
    viewController.m_nsLastText = str;
    UINavigationController *navigatitonController = [[[UINavigationController alloc]initWithRootViewController:viewController] autorelease];
	[self presentModalViewController:navigatitonController animated:YES];

}

-(void) sendVideoContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    NSDictionary *dic = [self.listArr objectAtIndex:self.sharedNum];
    message.title = @"超欢乐的视频，不看是你的损失哦";

    message.description = [dic objectForKey:@"title"];
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"icon"]];
    [message setThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]];

    WXVideoObject *ext = [WXVideoObject object];
    NSString *videoString = [[NSString alloc] initWithString:[dic objectForKey:@"playurl"]];
    [videoString stringByReplacingOccurrencesOfString:@" " withString:@""];
    ext.videoUrl =  videoString;
    [videoString release];
    //@"http://www.tudou.com/programs/view/6vx5h884JHY/?fr=1"
    message.mediaObject = ext;
    SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
    req.bText = NO;
    req.message = message;
    req.scene = _scene;
    [WXApi sendReq:req];
}
- (SinaWeibo *)sinaweibo
{
    KY_AppDelegate  *delegate = (KY_AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.sinaweibo.delegate = self;
    return delegate.sinaweibo;
}



@end
